package com.zqc.code.service.impl;

import com.zqc.code.dao.AuthCodeDao;
import com.zqc.code.model.AuthCode;
import com.zqc.code.remote.EmailService;
import com.zqc.code.service.AuthCodeService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Random;

@Service
public class AuthCodeServiceImpl implements AuthCodeService {
    @Autowired
    private AuthCodeDao authCodeDao;

    @Autowired
    private EmailService emailService;

    @Value("${authcode.expiretime}")
    private Long expiretime;

    @Override
    public boolean createAndSend(String email) {
        if (StringUtils.isEmpty(email)) {
            return false;
        }
        // 发送验证码
        String code = buildCode();
        Boolean con = emailService.sendEmail(email, code);
        System.out.println(con);
        if (con) {
            AuthCode authCode = new AuthCode();
            authCode.setEmail(email);
            authCode.setCode(code);
            Date date = new Date();
            authCode.setCreatetime(date);
            authCode.setExpiretime(new Date(date.getTime() + expiretime));
            authCodeDao.saveAndFlush(authCode);
            return true;
        }
        return false;
    }

    /**
     * 生成验证码
     * @return
     */
    private String buildCode() {
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < 6; i++) {
            sb.append(random.nextInt(10));
        }
        return sb.toString();
    }

    @Override
    public int validate(String email, String code) {
        AuthCode authCode = authCodeDao.findByEmailAndCode(email, code);
        if (authCode == null) {
            return 1;
        }
        Date expiretime = authCode.getExpiretime();
        if ((System.currentTimeMillis() - expiretime.getTime()) >= 0) {
            // 过期
            return 2;
        }

        return 0;
    }
}
